module.exports = {
	_before: function() { // 通用预处理器

	},

	// 🆕 获取利润记录 (支持按批次号和建材名称模糊查询)
	async getProfits({
		batch_no = null,
		material_name = null
	}) {
		const db = uniCloud.database();
		const profitCollection = db.collection('profit');
		const materialsCollection = db.collection('materials');

		// 并行执行查询
		const [profitRes, materialRes] = await Promise.all([
			// 查询利润记录，支持按批次号筛选
			batch_no ? profitCollection.where({
				batch_no
			}).get() : profitCollection.get(),
			// 查询建材记录，支持按建材名称模糊查询
			material_name ? materialsCollection.where({
				name: new RegExp(material_name, 'i')
			}).get() : materialsCollection.get()
		]);

		// 将所有建材名称保存到一个 Map 中，方便后续查找
		const materialMap = new Map();
		materialRes.data.forEach(material => {
			materialMap.set(material._id, material.name);
		});

		// 将建材名称添加到利润记录中，并过滤掉没有匹配建材名称的利润记录
		const profits = profitRes.data
			.map(profit => ({
				...profit,
				material_name: materialMap.get(profit.material_id) || ''
			}))
			.filter(profit => profit.material_name); // 只保留有匹配建材名称的利润记录

		return profits;
	},


	// 🆕 更新利润记录 (自动重新计算金额和净利润)
	async updateProfit({
		profitId,
		quantity,
		cost_price,
		sale_price
	}) {
		const db = uniCloud.database();

		// 获取当前记录
		const profit = await db.collection('profit').doc(profitId).get();
		if (profit.affectedDocs === 0) {
			return {
				code: 404,
				message: '利润记录不存在'
			};
		}

		// 自动重新计算金额和净利润
		const amount = sale_price * quantity;
		const net_profit = (sale_price - cost_price) * quantity;

		// 更新利润记录
		const res = await db.collection('profit').doc(profitId).update({
			quantity,
			cost_price,
			sale_price,
			amount,
			net_profit
		});
		return res;
	},

	// 🆕 获取利润记录 (支持按批次号和建材名称模糊查询)
	async getProfits({
		batch_no = null,
		material_name = null
	}) {
		const db = uniCloud.database();
		const profitCollection = db.collection('profit');
		const materialsCollection = db.collection('materials');

		// 查询利润记录，支持按批次号筛选
		let profitQuery = profitCollection;
		if (batch_no) {
			profitQuery = profitQuery.where({
				batch_no
			});
		}
		const profitRes = await profitQuery.get();

		// 如果传入了建材名称，进行模糊查询
		let materialQuery = materialsCollection;
		if (material_name) {
			materialQuery = materialQuery.where({
				name: new RegExp(material_name, 'i') // 使用正则表达式进行模糊查询 (忽略大小写)
			});
		}
		const materialRes = await materialQuery.get();

		// 将所有建材名称保存到一个 Map 中，方便后续查找
		const materialMap = new Map();
		materialRes.data.forEach(material => {
			materialMap.set(material._id, material.name);
		});

		// 将建材名称添加到利润记录中，并过滤掉没有匹配建材名称的利润记录
		const profits = profitRes.data
			.map(profit => {
				const material_name = materialMap.get(profit.material_id) || '';
				return {
					...profit,
					material_name
				};
			})
			.filter(profit => profit.material_name); // 只保留有匹配建材名称的利润记录

		return profits;
	},

	// 🆕 删除利润记录
	async deleteProfit({
		profitId
	}) {
		const db = uniCloud.database();
		const res = await db.collection('profit').doc(profitId).remove();
		return res;
	}
};